

let BaseView = require('../BaseView');

let templateDiv = `
    <label>已添加的修饰</label>
    <div id="deco_content" class="deco_content"></div>
`;

// let settings = require('../../settings');

class DecoView extends  BaseView{
    constructor(){
        super();

        this.rootEl = document.createElement('div');
        this.rootEl.classList.add('border');
        this.rootEl.innerHTML = templateDiv;

        this.contentEl = this.rootEl.querySelector('#deco_content');

        // lst
        this.model = [];
        this.updateModel(this.model);
    }

    reset(){

        let mapScene = editor.gameApp;

        if(mapScene){
            // 清除已经添加的修饰
            // 但是不清除 battery
            // battery占据了前2个
            let lstDeco = this.model;
            for (let i = 2, len = lstDeco.length; i < len; ++i) {
                let sp = lstDeco[i];
                sp.destroy();
            }
            lstDeco.length = 2;

            mapScene.sp_battery_1.node.angle = 0;
            mapScene.sp_battery_2.node.angle = 0;

            this.updateModel(lstDeco);
        }
    }

    getModel(){
        return this.model;
    }

    updateSpAlias(sp){
        let childEl = Array.prototype.find.call(this.contentEl.children,(childEl)=>{
            return childEl._sp === sp;
        });
        if(childEl){
            childEl.innerText = sp.alias;
        }
    }

    updateModel(newModel){
        if(newModel !== this.model){
            this.model = newModel;
        }
        this.updateList(this.model);
    }

    updateList(lstSprite){

        if(!lstSprite){
            throw new Error(`lstSprite is null!`);
        }

        // 释放dom,避免内存泄漏
        while (this.contentEl.children.length > 0){
            let firstChild = this.contentEl.firstChild;
            firstChild.onclick = null;
            firstChild._sp = null;
            this.contentEl.removeChild(firstChild);
        }
        this.contentEl.innerHTML = '';
        lstSprite.forEach(sp=>{
            this.addRow(sp);
        });
    }

    addRow(sp){
        let content = sp.id;
        let divEl = document.createElement('div');
        divEl.classList.add('deco_unselected');
        //divEl.setAttribute('contenteditable','false');

        if(sp.alias){
            divEl.innerText = sp.alias;
        }else{
            divEl.innerText = `Sprite_${content}`;
            sp.alias = divEl.innerText;
        }

        this.contentEl.appendChild(divEl);
        divEl._sp = sp;

        divEl.onclick = function () {
            // 选中
            let mapScene = editor.gameApp;
            mapScene.selectDeco(sp);
        };
    }

    selectSprite(sp){
        let children = this.contentEl.children;
        this.unselectAll();
        Array.prototype.forEach.call(children,divEl=>{
            if(divEl._sp === sp){
                divEl.classList.remove('deco_unselected');
                divEl.classList.add('deco_selected');
            }
        });
    }

    unselectAll(){
        let children = this.contentEl.children;
        Array.prototype.forEach.call(children,divEl=>{
            divEl.classList.remove('deco_selected');
        });
    }

    async_parseDeco(lstDecoData,resDir){

        if(lstDecoData.length < 1){
            return Promise.resolve();
        }

        cc.log('lstDecoData.length:',lstDecoData.length);

        let lstPromise = lstDecoData.map(decoProp=>{
            // 为了兼容
            if(!decoProp.img.startsWith('/')){
                decoProp.img = window.path.join(resDir,decoProp.img);
            }

            let mapScene = editor.gameApp;
            return new Promise(function (resolve, reject) {
                cc.assetManager.loadRemote(decoProp.img,(err,texture)=>{
                    if(err){
                        throw err;
                    }
                    let frame = new cc.SpriteFrame(texture);

                    let pos =  cc.v2(decoProp.x,decoProp.y);
                    let hole = !!decoProp.hole;
                    let degress = decoProp.degress;
                    let fog = !!decoProp.fog;
                    let lowerZ = !!decoProp.lowerZ;

                    let decoSprite = mapScene.onAddDecoSprite(decoProp.img,frame,pos);
                    decoSprite.hole = hole;
                    decoSprite.node.angle = degress;
                    decoSprite.fog = fog;
                    decoSprite.lowerZ = lowerZ;
                    if(decoProp.alias){
                        decoSprite.alias = decoProp.alias;
                    }
                    if(decoProp.anims && decoProp.anims.tempId > 0){
                        decoSprite.anims = decoProp.anims;
                    }else{
                        decoSprite.anims = null;
                    }

                    // TODO:忽略掉 width and height
                    // let width  = decoProp.width || decoSprite.texture.width;
                    // let height = decoProp.height || decoSprite.texture.height;
                    // decoSprite.setSize(width,height);

                    if(decoProp.hasOwnProperty('ax')){ // eslint-disable-line
                        decoSprite.node.anchorX = decoProp.ax;
                    }
                    if(decoProp.hasOwnProperty('ay')){ // eslint-disable-line
                        decoSprite.node.anchorY = decoProp.ay;
                    }

                    // 处理下z
                    let zIndex = decoProp.zIndex;
                    if(!(decoSprite.hole || decoSprite.fog || decoSprite.lowerZ)){
                        decoSprite.node.zIndex = zIndex;
                    }

                    resolve();
                });
            })
        });

        return Promise.all(lstPromise);
    }

    getDecoModel(){
        let arr = [];
        let lstMoveable = this.model;
        for(let i = 2,len = lstMoveable.length; i < len; ++i){
            let sp = lstMoveable[i];
            arr.push({
                x:~~sp.node.x,
                y:~~sp.node.y,
                ax:sp.node.anchorX,
                ay:sp.node.anchorY,
                degress:~~sp.node.angle,
                zIndex:sp.node.zIndex,
                alias:sp.alias,
                img:this._getBaseName(sp.decoPath),
                hole:sp.hole,
                fog:sp.fog, // 是否是迷雾
                lowerZ:sp.lowerZ, // 是否是 lowerZ
                // width:sp.width,
                // height:sp.height,
                anims:sp.anims,
            });
        }
        return arr;
    }

    _getBaseName(fp){
        return window.path.basename(fp);
    }
}

module.exports = DecoView;
